<template>
  <div class="code-layout">

    <!-- <div class="code-materials" v-if="detailData">
      <div>
        <plug-state :statusStr="status" v-if="status" />
        <br />
      </div>
      <div class="file">
        <file-list :biz_id="detailData.id" type="build-image" />
      </div>
    </div> -->

    <div class="code-info">
      <div class="code-info-item">
        <h3 class="info-title">基本信息<i class="el-icon-edit-outline edit" @click="updateBase" /></h3>
        <ul class="info-item">
          <li>
            <span class="key">名称:</span>
            <span class="val">{{ detailData.name }}</span>
          </li>
          <li>
            <span class="key">类型： </span>
            <span class="val">{{ detailData.type }}</span>
          </li>
          <li>
            <span class="key"> 创建人： </span>
            <span class="val">{{
              detailData.create_user && (detailData.create_user &&
                detailData.create_user.nick_name ||
                detailData.create_user && detailData.create_user.username)
            }}</span>
          </li>
          <li>
            <span class="key">创建时间： </span>
            <span class="val">{{ detailData.create_time }}</span>
          </li>
        </ul>
      </div>

      <div class="code-info-item">
        <h3 class="info-title" v-if="this.formData.build_type == '1'">Dockfile信息 <i class="el-icon-edit-outline edit"
            @click="updateDockfile" /></h3>
        <ul class="info-item" v-if="fromImage">
          <li>
            <span class="key">基础环境:</span>
            <span class="val">{{ fromImage.name }}</span>
          </li>
        </ul>
      </div>
    </div>

    <!-- <el-dialog :visible.sync="showUpdateBaseDialog" title="我的环境基本信息" width="840px">
      <el-form class="form myself-form" ref="form" :rules="submitRules" :model="formData" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="formData.name" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="formData.desc" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="formData.type" @change="changeEngine()">
            <el-radio :label="1">训练</el-radio>
            <el-radio :label="2">推理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label=" ">
          <el-button class="none-type" type="primary" @click="commitBase">确定</el-button>
          <el-button class="none-type" @click="cancelBase">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog> -->

    <!-- <el-dialog :visible.sync="showUpdateDockfileDialog" title="环境基本信息" width="840px">
      <el-form class="form myself-form" ref="form" :model="formData" label-width="120px">
        <el-form-item v-if="formData.type == 1" label="框架" prop="name">
          <el-radio-group v-model="formData.engine" size="small" @change="changeEngine()">
            <el-radio-button label='2'>Pytorch</el-radio-button>
            <el-radio-button label='1'>TensorFlow</el-radio-button>
            <el-radio-button label='3'>其他</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="基础环境" prop="name">
          <div class="select">
            <el-select v-model="fromImage" value-key="id" @change="changFromImage" class="full-extent-select">
              <el-option v-for="item in imageOptions" :value="item" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="Dockfile" prop="name">
          <code-editor :style="{ height: '260px' }" ref="jsonEditor" mode="dockerfile" v-model="dockerFile" />
        </el-form-item>
        <el-form-item label=" ">
          <el-button class="none-type" type="primary" @click="commitDockfile">确定</el-button>
          <el-button class="none-type" @click="cancelDockfile">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog> -->

    <DialogBox title="我的环境基本信息" :visible="showUpdateBaseDialog" :confirm="commitBase" :close="cancelBase">
      <el-form class="form myself-form" ref="form" :rules="submitRules" :model="formData" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="formData.name" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="formData.desc" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="formData.type" @change="changeEngine()">
            <el-radio :label="1">训练</el-radio>
            <el-radio :label="2">推理</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </DialogBox>

    <DialogBox title="环境基本信息" :visible="showUpdateDockfileDialog" :confirm="commitDockfile" :close="cancelDockfile">
      <el-form class="form myself-form" ref="form" :model="formData" label-width="120px">
        <el-form-item v-if="formData.type == 1" label="框架" prop="name">
          <el-radio-group v-model="formData.engine" size="small" @change="changeEngine()">
            <el-radio-button label='2'>Pytorch</el-radio-button>
            <el-radio-button label='1'>TensorFlow</el-radio-button>
            <el-radio-button label='3'>其他</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="基础环境" prop="name">
          <div class="select">
            <el-select v-model="fromImage" value-key="id" @change="changFromImage" class="full-extent-select">
              <el-option v-for="item in imageOptions" :value="item" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="Dockfile" prop="name">
          <code-editor :style="{ height: '260px' }" ref="jsonEditor" mode="dockerfile" v-model="dockerFile" />
          <!-- <el-input type="textarea" v-model="dockerFile" :rows="12" :v-model="formData.dockerFile" /> -->
        </el-form-item>
      </el-form>
    </DialogBox>
  </div>
</template>

<script>
import DialogBox from '@/components/module/dialog-box.vue';
import { getImageDetail, putImage, getAllImages, } from '@/api/images'
import CodeEditor from "@/components/module/CodeEditor";
import { previewFile, uploadFile } from "@/api/file"
import { Base64 } from "js-base64";
export default {
  data() {
    return {
      status: null,
      fromImage: null,
      showUpdateDockfileDialog: false,
      dockerFile: '',
      imageOptions: [],
      formData: {},
      showUpdateBaseDialog: false,
      submitRules: {
        name: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        desc: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 200, message: "长度在1到200个字符" },
        ],
      },
    };
  },

  props: ['detailData'],
  watch: {
    detailData(val) {
      this.status = val.status;
      this.formData = val
    },
  },
  async created() {
    console.log("detailData", this.detailData)
    this.getFormData()
  },
  components: {
    CodeEditor,
    DialogBox,
  },

  async mounted() {
    this.$nextTick(() => {
      this.status = this.detailData.status;
    })
    this.changeEngine()
  },
  destroyed() {

  },
  methods: {
    updateBase() {
      this.formData = { ...this.detailData }
      this.showUpdateBaseDialog = true
    },

    commitBase() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res = await putImage(this.formData);
          if (res && res.data) {
            this.$emit("getDetail")
            this.showUpdateBaseDialog = false
          }
        }
      })
    },
    cancelBase() {
      this.showUpdateBaseDialog = false
    },

    editState(state) {
      console.log(state)
    },
    async changeEngine() {
      if (this.formData.type == 1) {
        let res = await getAllImages({ visibility: '2', engine: this.formData.engine, type: this.formData.type })
        this.imageOptions = res.data
      }
      else {
        let res = await getAllImages({ visibility: '2', type: this.formData.type })
        this.imageOptions = res.data
      }
    },
    async getFormData() {
      this.formData = JSON.parse(JSON.stringify(this.detailData))
      this.status = this.formData.status;
      let res = await getImageDetail({ id: this.detailData.id })
      this.fromImage = res.data
      if (this.formData.build_type == '1') {
        this.previewDockfile()
      }
    },
    updateDockfile() {
      this.showUpdateDockfileDialog = true
    },
    dataURLtoFile(dataurl, filename) {
      //将base64转换为文件
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    async writeFile() {
      let data = new FormData()
      let filesFile = this.dataURLtoFile(
        `data:text/markdown;base64,${Base64.encode(this.dockerFile)}`,
        'Dockerfile'
      )
      console.log(this.dockerFile)
      let myInfo = await this.$myInfo(this)
      data.append("chunkNumber", 1)
      data.append("totalChunks", 1)
      data.append("repeType", '')
      data.append("filename", filesFile.name)
      data.append("relativePath", '/Dockerfile')
      data.append("userId", myInfo.id)
      data.append("type", 'build-image')
      data.append("bizId", this.detailData.id)
      data.append("file", new Blob([filesFile]), filesFile.name)

      return await uploadFile(data)
    },
    commitDockfile() {
      //this.setFormData()
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          await this.writeFile()
          let res = await putImage({ ...this.image, ...this.formData })
          if (res && res.data) {
            this.showUpdateDockfileDialog = false
            this.freshData()
          }
        }
      })
    },
    cancelDockfile() {
      this.showUpdateDockfileDialog = false
    },
    async freshData() {
      let res = await getImageDetail({ id: this.detailData.id });
      if (res && res.data) {
        this.$emit('update:detailData', res.data);
        this.getFormData()
      }
    },
    changFromImage() {
      if (this.fromImage) {
        this.formData.base_image_id = this.fromImage.id
        this.dockerFile = 'FROM  ' + this.fromImage.url
      }
    },
    async previewDockfile() {
      let myInfo = await this.$myInfo(this)
      let encodedRelativePath = encodeURIComponent(Base64.encode('/Dockerfile'))
      let [err, res] = await this.$awaitWrap(previewFile({
        bizId: this.detailData.id,
        encodedRelativePath,
        type: "build-image",
        userId: myInfo.id,
      }))
      console.log("err", err)
      this.dockerFile = res
    },
  }
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/code.less";
</style>
